package com.omega.exam.service.impl;


import com.omega.exam.config.MinioProperties;
import com.omega.exam.service.FileUploadService;
import io.minio.*;


import io.minio.errors.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * projectName: com.atguigu.exam.service.impl
 *
 * @author: 赵伟风
 * description:
 */
@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {
    @Resource
    private MinioClient minioClient;
    @Resource
    private MinioProperties minioProperties;
    public     String uploadFile(MultipartFile file, String folder) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        Boolean bucketexist=minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        System.out.println(minioProperties.getBucketName());
        System.out.println(minioProperties.getAccesskey());
        System.out.println(minioProperties.getSecretKey());
        if(!bucketexist){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            String config = """
                        {
                              "Statement" : [ {
                                "Action" : "s3:GetObject",
                                "Effect" : "Allow",
                                "Principal" : "*",
                                "Resource" : "arn:aws:s3:::%s/*"
                              } ],
                              "Version" : "2012-10-17"
                        }
                    """.formatted(minioProperties.getBucketName());
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(config).build());
        }
        String objectName=folder+"/"+new SimpleDateFormat("yyyyMMdd").format(new Date())+"/"+ UUID.randomUUID().toString().replaceAll("-","")+"_"+ file.getOriginalFilename();
        minioClient.putObject(PutObjectArgs.builder().bucket(minioProperties.getBucketName()).contentType(file.getContentType()).object(objectName).stream(file.getInputStream(),file.getSize(),-1).build());
        String url=String.join("/",minioProperties.getEndpoint(),minioProperties.getBucketName(),objectName);
        return url;

    }
}
